package org.jeecg.modules.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.modules.xetuser.service.IXetUserService;
import org.jeecg.modules.config.CustomProperties;
import org.jeecg.modules.service.ApiWxUserInfoService;
import org.jeecg.modules.service.wx.WeixinService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.weixin4j.WeixinException;
import org.weixin4j.model.sns.SnsUser;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author guoyh
 * @ClassName LoginController
 * @Description
 * @since 2020/8/11 00:54
 *
 * 扫码事件
 **/
@Controller
@Slf4j
public class LoginController extends BaseController{
    private String goXeStudioUrl = "https://appigc72vmw2720.h5.xiaoeknow.com/mp/";
    private static final String APP_HEADER = "medicalwisdom";

    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private CustomProperties customProperties;
    @Resource
    private ApiWxUserInfoService apiWxUserInfoService;
    @Resource
    private WeixinService weixinService;
    @Resource
    private IXetUserService xetUserService;

    /**
     * 公众号授权地址
     * @param code
     * @param url
     * @param from
     * @param state
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("auth")
    public void login(@RequestParam(value = "code",required = false) String code,
                        @RequestParam(value = "url") String url,
                        @RequestHeader(required = false,value = "from") String from,
                        @RequestParam(value = "state",required = false)String state,
                        HttpServletResponse response) throws IOException {
        log.info("header data:{}",from);
        if (StringUtils.isNotBlank(from) && StringUtils.equals(from,APP_HEADER)){
            response.sendRedirect(url);
//            return null;
        }

        log.info("state：{}",state);
        //兼容大医智慧第一版相关功能使用
        if(StringUtils.startsWith(url,"https://xcx.bjjk.com/") || StringUtils.startsWith(url,"http://xcx.bjjk.com/")){
            response.sendRedirect(url.concat("?code=").concat(code).concat("&state=").concat(state));
//            return null;
        }

        //体质辨识测评项目
        if(StringUtils.startsWith(url,"http://media.dyzh120.com/")){
            response.sendRedirect(url.concat("?code=").concat(code).concat("&state=").concat(state));
//            return null;
        }
        if (StringUtils.isBlank(code)){
            String urlParam = customProperties.getH5ApiDomain().concat("/auth?url=").concat(url);
            String redirectUrl = weixinTemplate.sns().getOAuth2CodeBaseUrl(urlParam);
            log.info("重定向url:{}",redirectUrl);
            response.sendRedirect(redirectUrl);
//            return null;
        }
        try {
            log.info("根据code获取openid：{}",code);

            SnsUser snsUser = weixinTemplate.sns().getSnsUserByCode(code);
            log.info("获取到的用户信息:{}", JSONUtil.toJsonStr(snsUser));

            weixinService.getOrCreateWxUserinfo(snsUser);
            url = url.replaceAll("!!!","&");
            log.info("要跳转的链接：{}",url);
            String openId = snsUser.getOpenid();

            log.info("当前用户h5 openid:{}",snsUser.getOpenid());
//            getLoginUser().setOpenid(openId);
//            log.info("当前用户h51 openid:{}",getLoginUser().getOpenid());
            // 判断是否是跳转到小鹅通
            //                                   https://appigc72vmw2720.h5.xiaoeknow.com
            if(StringUtils.startsWith(url,"https://appigc72vmw2720.h5.xiaoeknow.com/")){
                log.info("小鹅通：请求跳转");
                // 处理用户医生关系
                String[] urlArr = url.split("=");
                String pageId = urlArr[urlArr.length - 1];
                log.info("小鹅通页面 pageId:{}",pageId);
                log.info("当前用户 openid:{}",snsUser.getOpenid());

                String xetUrl = xetUserService.xetUrl(snsUser.getOpenid(),pageId);
                response.sendRedirect(xetUrl);
            }else{
                String accessToken = apiWxUserInfoService.login(snsUser);
                log.info("用户登陆accessToken:{}",accessToken);
                log.info("用户登陆accessToken:{}1",url.concat(accessToken));
                log.info("用户登陆accessToken:{}2",url);
                response.sendRedirect(url.concat(accessToken));
            }

//            return null;
        } catch (WeixinException e) {
            log.error("获取微信openid失败",e);
        }
//        return null;
    }
}
